<template>
  <div class="dashboard-editor-container">

    <panel-group @handleSetLineChartData="handleSetLineChartData" />

    <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
      <line-chart :chart-data="currentChartData" />
    </el-row>

   <!-- <el-row :gutter="32">
      <el-col :xs="24" :sm="24" :lg="8">
        <div class="chart-wrapper">
          <raddar-chart />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="8">
        <div class="chart-wrapper">
          <pie-chart />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="8">
        <div class="chart-wrapper">
          <bar-chart />
        </div>
      </el-col>
    </el-row> -->
    <AIFloatingButton />

  </div>
</template>

<script>
import PanelGroup from './dashboard/PanelGroup'
import LineChart from './dashboard/LineChart'
// import RaddarChart from './dashboard/RaddarChart'
// import PieChart from './dashboard/PieChart'
// import BarChart from './dashboard/BarChart'
import { getUserJoinStats, getCommentStats } from '@/api/foodworks/comments'
import AIFloatingButton from '@/components/AIFloatingButton.vue'
export default {
  name: 'Index',
  components: {
    PanelGroup,
    LineChart,
    AIFloatingButton
    // RaddarChart,
    // PieChart,
    // BarChart
  },
  data() {
    return {
      lineChartData: {
        newVisitis: {
          expectedData: [100, 120, 161, 134, 105, 160, 165],
          actualData: [120, 82, 91, 154, 162, 140, 145]
        },
        messages: {
          expectedData: [0, 0, 0, 0, 0, 0, 0], // 评论数量，将被动态替换
          actualData: [0, 0, 0, 0, 0, 0, 0] // 用户加入数量，将被动态替换
        },
        purchases: {
          expectedData: [80, 100, 121, 104, 105, 90, 100],
          actualData: [180, 160, 151, 106, 145, 150, 130]
        },
        shoppings: {
          expectedData: [130, 140, 141, 142, 145, 150, 160],
          actualData: [120, 82, 91, 154, 162, 140, 130]
        }
      },
      currentChartType: 'newVisitis' // 当前选中的图表类型
    }
  },
  async created() {
    await this.loadUserJoinStats()
    await this.loadCommentStats()
  },
  methods: {
    handleSetLineChartData(type) {
      this.currentChartType = type
      // 强制更新图表数据
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },

    // 获取用户加入统计
    async loadUserJoinStats() {
      try {
        console.log('开始获取用户加入统计...')
        const response = await getUserJoinStats()
        console.log('用户加入API响应:', response)

        if (response.code === 200) {
          const dailyStats = this.processUserJoinStats(response.data)
          console.log('处理后的用户加入统计数据:', dailyStats)

          // 更新messages的actualData（用户加入数量）
          this.lineChartData.messages.actualData = [...dailyStats]

          // 强制更新组件
          this.$nextTick(() => {
            this.$forceUpdate()
            console.log('用户加入图表数据已更新:', this.lineChartData.messages.actualData)
          })
        } else {
          console.error('用户加入API返回错误:', response.msg)
          this.lineChartData.messages.actualData = [0, 0, 0, 0, 0, 0, 0]
        }
      } catch (error) {
        console.error('获取用户加入统计失败:', error)
        // 使用默认值
        this.lineChartData.messages.actualData = [0, 0, 0, 0, 0, 0, 0]
      }
    },

    // 获取评论统计
    async loadCommentStats() {
      try {
        console.log('开始获取评论统计...')
        const response = await getCommentStats()
        console.log('评论API响应:', response)

        if (response.code === 200) {
          const dailyStats = this.processCommentStats(response.data)
          console.log('处理后的评论统计数据:', dailyStats)

          // 更新messages的expectedData（评论数量）
          this.lineChartData.messages.expectedData = [...dailyStats]

          // 强制更新组件
          this.$nextTick(() => {
            this.$forceUpdate()
            console.log('评论图表数据已更新:', this.lineChartData.messages.expectedData)
          })
        } else {
          console.error('评论API返回错误:', response.msg)
          this.lineChartData.messages.expectedData = [0, 0, 0, 0, 0, 0, 0]
        }
      } catch (error) {
        console.error('获取评论统计失败:', error)
        // 使用默认值
        this.lineChartData.messages.expectedData = [0, 0, 0, 0, 0, 0, 0]
      }
    },

    // 处理用户加入统计数据
    processUserJoinStats(statsData) {
      console.log('原始用户加入统计数据:', statsData)

      // 将后端返回的数据转换为7天数组 [一天前, 二天前, 三天前, 四天前, 五天前, 六天前, 七天前]
      const result = [0, 0, 0, 0, 0, 0, 0]

      if (statsData && Array.isArray(statsData)) {
        statsData.forEach(item => {
          console.log('处理用户加入数据项:', item)
          const daysDiff = this.getDaysDiff(new Date(item.join_date))
          console.log('用户加入日期差:', daysDiff, '日期:', item.join_date)

          if (daysDiff >= 0 && daysDiff < 7) {
            result[6 - daysDiff] = item.user_count
          }
        })
      } else {
        console.warn('用户加入统计数据不是数组或为空:', statsData)
      }

      console.log('用户加入最终结果:', result)
      return result
    },

    // 处理评论统计数据
    processCommentStats(statsData) {
      console.log('原始评论统计数据:', statsData)

      // 将后端返回的数据转换为7天数组 [一天前, 二天前, 三天前, 四天前, 五天前, 六天前, 七天前]
      const result = [0, 0, 0, 0, 0, 0, 0]

      if (statsData && Array.isArray(statsData)) {
        statsData.forEach(item => {
          console.log('处理评论数据项:', item)
          const daysDiff = this.getDaysDiff(new Date(item.comment_date))
          console.log('评论日期差:', daysDiff, '日期:', item.comment_date)

          if (daysDiff >= 0 && daysDiff < 7) {
            result[6 - daysDiff] = item.comment_count
          }
        })
      } else {
        console.warn('评论统计数据不是数组或为空:', statsData)
      }

      console.log('评论最终结果:', result)
      return result
    },

    // 计算日期差
    getDaysDiff(date) {
      const today = new Date()
      // 重置时间为00:00:00，只比较日期
      today.setHours(0, 0, 0, 0)
      date.setHours(0, 0, 0, 0)

      const diffTime = today - date
      const daysDiff = Math.floor(diffTime / (1000 * 60 * 60 * 24))
      console.log('计算日期差:', { today: today.toDateString(), date: date.toDateString(), daysDiff })
      return daysDiff
    }
  },

  // 计算属性：获取当前图表数据
  computed: {
    currentChartData() {
      return this.lineChartData[this.currentChartType] || this.lineChartData.newVisitis
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
